import java.util.*;

/*
题目：前k个高频元素
给你一个整数数组 nums 和一个整数 k ，请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
https://leetcode.cn/problems/top-k-frequent-elements/
 */
public class TopKFrequentNum {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<> ();
        for (int x : nums) {
            if (map.containsKey(x)) {
                int val = map.get(x);
                map.put(x, val + 1);
            } else {
                map.put(x, 1);
            }
        }

        PriorityQueue<Map.Entry<Integer, Integer>> minHeap =
                new PriorityQueue<> (new Comparator<Map.Entry<Integer, Integer>>() {
                    public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                        return o1.getValue().compareTo(o2.getValue());
                    }
                });
        Set<Map.Entry<Integer, Integer>> set = map.entrySet();
        for (Map.Entry<Integer, Integer> entry : set) {
            if (minHeap.size() < k) {
                minHeap.offer(entry);
            } else {
                Map.Entry<Integer, Integer> top = minHeap.peek();
                if (top.getValue().compareTo(entry.getValue()) < 0) {
                    minHeap.poll();
                    minHeap.offer(entry);
                }
            }
        }

        int[] ans = new int[k];
        for (int i = k - 1; i >= 0; i--) {
            ans[i] = minHeap.poll().getKey();
        }
        return ans;
    }
}
